package com.mo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mo.common.Result;
import com.mo.entity.PageVo;
import com.mo.entity.Role;
import com.mo.service.RoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("role")
public class RoleController {
    @Resource
    private RoleService roleService;

    @PostMapping
    @PreAuthorize("hasAuthority('sys:system:role:add')")
    public Result addRole(@RequestBody Role role) {
        boolean success = roleService.save(role);
        if (success) {
            return Result.success();
        }
        return Result.error();
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('sys:system:role:delete')")
    public Result removeRole(@RequestParam String roleId) {
        boolean success = roleService.removeById(roleId);
        if (success) {
            return Result.success();
        }
        return Result.error();
    }

    @PutMapping
    @PreAuthorize("hasAuthority('sys:system:role:update')")
    public Result updateRole(@RequestBody Role role) {
        boolean success = roleService.updateById(role);
        if (success) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping
    public Result selectRole(@RequestParam Long pageNum, @RequestParam Long pageSize) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.<Role>lambdaQuery();
        Page<Role> page = roleService.page(new Page<>(pageNum, pageSize), wrapper);
        PageVo<Role> rolePageVo = new PageVo<>();
        rolePageVo.setPageNum(pageNum);
        rolePageVo.setPageSize(pageSize);
        rolePageVo.setTotal(page.getTotal());
        rolePageVo.setList(page.getRecords());
        return Result.success(rolePageVo);
    }
}
